package com.tarena.lbs.content.dao.repository.impl;

import com.tarena.lbs.content.dao.repository.ArticleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.stream.Collectors;

@Repository
@RequiredArgsConstructor
public class ArticleRepositoryImpl implements ArticleRepository {
    private final RedisTemplate<String, Object> redisTemplate;
    private final HashOperations<String, String, Object> hashOperations;
    @Autowired
    public ArticleRepositoryImpl(RedisTemplate<String, Object> redisTemplate){
        this.redisTemplate = redisTemplate;
        hashOperations = redisTemplate.opsForHash();
    }
    @Override
    public void saveFieldToArticle(Integer articleId, String field, Integer value) {
        hashOperations.put("article:"+articleId, field, value);
    }
    @Override
    public void saveAllFieldsToArticle(Integer articleId, Map<String, Integer> fields) {
        hashOperations.putAll("article:"+articleId, fields);
    }
    @Override
    public Integer getFieldFromArticle(Integer articleId, String field) {
        return (Integer) hashOperations.get("article:"+articleId, field);
    }
    @Override
    public Map<String, Integer> getAllFieldsFromArticle(Integer articleId) {
        Map<String, Object> rawMap = hashOperations.entries("article:" + articleId);
        return rawMap.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        e -> Integer.parseInt(e.getValue().toString())
                ));
    }
}
